﻿using Core.Framework;
using DotNetty.Framework;
using DotNetty.Framework.BaseTriggers;
using Grain.Interfaces;
using iTool.ClusterComponent;
using Orleans;
using System.Threading.Tasks;

namespace iTool.Connector.CommandWorkers
{
    /// <summary>
    /// 订阅
    /// </summary>
    [Worker("iTool")]
    public class SubscribeChannelWorker : WorkerController
    {
        private iToolClusterHostClient iCluster;

        public SubscribeChannelWorker(iToolClusterHostClient cluster)
        {
            this.iCluster = cluster;
        }

        [MethodRoute("Subscribe Channel")]
        public async Task<DoWorkResponse> Subscribe(HandleDoWorkingContext context)
        {
            // 当前channel
            var channel = context.ChannelHandlerContext.GetChannel();
            if (string.IsNullOrWhiteSpace(channel))
            {
                return this.GetErrorResponseOfParameterValidationFailed(context, "channel is null");
            }

            var topic = context.Message.Parameter;

            var iTopic = this.iCluster.GetService<IChannelService>(channel);
            await iTopic.Subscribe(topic);
            context.ChannelHandlerContext.Subscribe(topic);

            return this.GetWorkResponse(context, topic);
        }

        [MethodRoute("UnSubscribe Channel")]
        public async Task<DoWorkResponse> UnSubscribe(HandleDoWorkingContext context)
        {
            // 当前channel
            var channel = context.ChannelHandlerContext.GetChannel();
            if (string.IsNullOrWhiteSpace(channel))
            {
                return this.GetErrorResponseOfParameterValidationFailed(context, "channel is null");
            }

            var topic = context.Message.Parameter;

            var iTopic = this.iCluster.GetService<IChannelService>(channel);
            await iTopic.UnSubscribe(topic);
            context.ChannelHandlerContext.UnSubscribe(topic);

            return this.GetWorkResponse(context, topic);
        }
    }
}
